    //
//  SlideViewController.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/10.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SlideViewController.h"
#import "PageViewController.h"
#import "UserSlidePageViewController.h"
#import "MultipleChoicePageViewController.h"
#import "ShortAnswerPageViewController.h"
#import "CategoryPageViewController.h"
#import "DesignerPageViewController.h"
#import "NavigatorPageViewController.h"
#import "ScoreReportPageViewController.h"
#import "AD_Page.h"
#import "GDataXMLNode.h"
#import "AD_ContainerOB.h"
#import "ParallaxPageViewController.h"



@implementation SlideViewController
@synthesize PageOBs, pageVCSets , PID, userData, PresentName, SlideOB, PageID, KioskOB, GPageIndex, numberCorrect, numberIncorrect, allPages,ContainOB, SlideIndex,SlideCount, isForPDF, canExportToPDF;


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

#pragma mark -
#pragma mark Delegate Function Sets

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}


-(void)leavePresentation
{
    [_delegate newPresentation];
}

-(void)idleReset
{
    [_delegate resetIdleTimer];
}

- (void)ShowCamera:(PageViewController *)sender
{
    [_delegate ShowCamera:sender];
}

-(void)exportPDF
{
    NSMutableArray *currentPosition = [[NSMutableArray alloc] initWithCapacity:2];
    [currentPosition addObject:[NSNumber numberWithInt:SlideOB.SlideID]];
    [currentPosition addObject:[NSNumber numberWithInt:PageID]];
    
    [_delegate exportToPDF:currentPosition];  
}

-(void)LeaveSection:(int)NewSectionID
          NewPageID:(int)NewPageID
{
    if(NewSectionID == SlideOB.SlideID)
        [self jumpToPage:NewPageID];
    else
        [_delegate jumpSection:NewSectionID
                    oldSection:SlideOB.SlideID
                      jumpPage:NewPageID];
}

- (void)updateSubmitStatus
{
    SlideOB.Submit = TRUE;
}

-(void)updateCorrectAnswers:(int)numCorrect :(int)numIncorrect{
    numberCorrect = numCorrect;
    numberIncorrect = numIncorrect;
    
    [_delegate updateAnswerCount:numberCorrect :numberIncorrect];
}

-(void)jumpToPage:(int)NewPageID {
    [self jumpToPage:NewPageID recordHistory:YES];
}

-(void)jumpToPage:(int)NewPageID recordHistory:(BOOL)shouldRecord
{
    int i=0;
    for(AD_Page *pageOB in PageOBs)
    {
        if(pageOB.pageID == NewPageID)
        {
            [self changePage:i
                   direction:UIViewAnimationDirectionForward recordHistory:shouldRecord];
            break;
        }
        i++;
    }
}

- (void)SaveIntoFile
{
    [_delegate SaveIntoFile];
}

#pragma mark -
#pragma mark iOS default View  Load

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	userData = [self XMLBuilder];
	
	NSMutableArray *nilControllers = [[NSMutableArray alloc] init];
	
	for (unsigned i =0; i <[PageOBs count]; i++)
		[nilControllers addObject:[NSNull null]];
	
	
	self.pageVCSets = nilControllers;
	[nilControllers release];
    
    
    int initialIndex = 0; 
    
    if(PageID != 0)
        initialIndex= [[SlideOB.PageIdLookup objectForKey:[NSNumber numberWithInt:PageID]] intValue];
	
	[self loadViewWithPage:initialIndex display:YES recordToHistory:YES];
	//[self loadViewWithPage:initialIndex+1 display:NO];
	
}

-(void)changePage:(int)pageIndex direction:(UIViewAnimationDirection)direction recordHistory:(BOOL)shouldRecord{
    [self loadViewWithPage:pageIndex display:YES direction:direction doTransition:YES recordToHistory:YES];
	[self loadViewWithPage:pageIndex +1 display:NO recordToHistory:NO];
	[self loadViewWithPage:pageIndex -1 display:NO recordToHistory:NO];
    
    [self unloadViews:pageIndex];
}

-(void)changePage:(int)pageIndex direction:(UIViewAnimationDirection)dir
{
    [self changePage:pageIndex direction:dir recordHistory:YES];
}

-(void)unloadViews:(int)pIndex
{
    for (int i=0 ; i< [pageVCSets count]; i++) {
        if(i != pIndex && i!= pIndex +1 && i!=pIndex-1)
            [self unloadViewWithPage:i];
    }
}

-(GDataXMLElement *)XMLBuilder{
	GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"UserData"];
	GDataXMLNode *defaultNamespace = [GDataXMLNode attributeWithName:@"xmlns" stringValue:@"http://www.activedeck.com/PowerPoint/"];
	GDataXMLNode *Presentation = [GDataXMLNode attributeWithName:@"Presentation" stringValue:PID];
	GDataXMLNode *Section = [GDataXMLNode attributeWithName:@"Section" stringValue:[NSString stringWithFormat:@"%d", SlideOB.SlideID]];
	[rootElement addChild:Presentation];
	[rootElement addChild:Section];
	[rootElement addChild:defaultNamespace];
	[rootElement addChild:userData];
	
	return rootElement;
}

- (void) viewDidAppear:(BOOL)animated
{
    [[pageVCSets objectAtIndex:GPageIndex]viewDidAppear:animated];
}

-(void)loadViewWithPage:(int)pageIndex 
                display:(BOOL)show
        recordToHistory:(BOOL)shouldRecord{
    
    [self loadViewWithPage:pageIndex 
                   display:show 
                 direction:UIViewAnimationDirectionForward
              doTransition:YES
     recordToHistory:shouldRecord];
}

-(void)loadViewWithPage:(int)pageIndex display:(BOOL)show doTransition:(BOOL)shouldAnimate recordToHistory:(BOOL)shouldRecord{
    [self loadViewWithPage:pageIndex display:show direction:UIViewAnimationDirectionForward doTransition:shouldAnimate recordToHistory:shouldRecord];
}

-(void)loadViewWithPage:(int)pageIndex 
                display:(BOOL)show 
              direction:(UIViewAnimationDirection)direction
           doTransition:(BOOL)shouldAnimate
        recordToHistory:(BOOL)shouldRecord{
	if(pageIndex <0 || pageIndex >= [PageOBs count])
		return;
    
    AD_Page *PageOB = [PageOBs objectAtIndex:pageIndex];
    
    if(!PageOB.display)
    {
        [self loadViewWithPage:pageIndex + 1 display:TRUE recordToHistory:shouldRecord];
        return;
    }
    
    if(PageOB.oneTime)
        PageOB.display = FALSE;
    
    GPageIndex = pageIndex;
    
	UserSlidePageViewController *usPageVC;
	ShortAnswerPageViewController *saPageVC;
	MultipleChoicePageViewController *mcPageVC;
	CategoryPageViewController *caPageVC;
    DesignerPageViewController *dsPageVC;
    NavigatorPageViewController *ngPageVC;
    ScoreReportPageViewController *srPageVC;
    ParallaxPageViewController *plPageVC;
	

	
	if([PageOB.pageType isEqualToString:@"CurrentSlide"] || [PageOB.pageType isEqualToString:@"UserSlide"])
	{
		usPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)usPageVC == [NSNull null])
		{
			usPageVC = [[UserSlidePageViewController alloc] init];
			usPageVC.pageOB = PageOB;
			usPageVC.userData = userData;
			usPageVC.PID = [PID intValue];
            usPageVC.PresentName = PresentName;
			usPageVC.SlideID = SlideOB.SlideID;
			usPageVC.PageCount = [PageOBs count];
            usPageVC.Kiosk = KioskOB;
            usPageVC.Show = show;
            usPageVC.containOB = ContainOB;
            usPageVC.SlideIndex = SlideIndex;
            usPageVC.SlideCount = SlideCount;
            usPageVC.isForPDF = isForPDF;
            usPageVC.canExportToPDF = canExportToPDF;
            usPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            usPageVC.canNavigateForwards = PageOB.canNavigateForwards;

			[usPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:usPageVC];
			[usPageVC release];
		}
		
		if(show)
		{
            usPageVC.numberCorrect = numberCorrect;
            usPageVC.numberIncorrect = numberIncorrect;
            
            [usPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}
	}
    else if([PageOB.pageType isEqualToString:@"NavigatorSlide"])
	{
		ngPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)ngPageVC == [NSNull null])
		{
			ngPageVC = [[NavigatorPageViewController alloc] init];
			ngPageVC.pageOB = PageOB;
			ngPageVC.userData = userData;
			ngPageVC.PID = [PID intValue];
            ngPageVC.PresentName = PresentName;
			ngPageVC.SlideID = SlideOB.SlideID;
			ngPageVC.PageCount = [PageOBs count];
            ngPageVC.Kiosk = KioskOB;
            ngPageVC.Show = show;
            ngPageVC.containOB = ContainOB;
            ngPageVC.SlideIndex = SlideIndex;
            ngPageVC.SlideCount = SlideCount;
            ngPageVC.isForPDF = isForPDF;
            ngPageVC.canExportToPDF = canExportToPDF;
            ngPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            ngPageVC.canNavigateForwards = PageOB.canNavigateForwards;
            
            [self recordNavigationHistory:(shouldRecord && PageOB.trackNavigation) :PageOB.pageID :SlideIndex];
            
			[ngPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:ngPageVC];
			[ngPageVC release];
            
            
		}
		
		if(show)
		{
            ngPageVC.numberCorrect = numberCorrect;
            ngPageVC.numberIncorrect = numberIncorrect;

            [ngPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}
	}else if([PageOB.pageType isEqualToString:@"ParallaxSlide"])
	{
		plPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)ngPageVC == [NSNull null])
		{
			plPageVC = [[ParallaxPageViewController alloc] init];
			plPageVC.pageOB = PageOB;
			plPageVC.userData = userData;
			plPageVC.PID = [PID intValue];
            plPageVC.PresentName = PresentName;
			plPageVC.SlideID = SlideOB.SlideID;
			plPageVC.PageCount = [PageOBs count];
            plPageVC.Kiosk = KioskOB;
            plPageVC.Show = show;
            plPageVC.containOB = ContainOB;
            plPageVC.SlideIndex = SlideIndex;
            plPageVC.SlideCount = SlideCount;
            plPageVC.isForPDF = isForPDF;
            plPageVC.canExportToPDF = canExportToPDF;
            plPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            plPageVC.canNavigateForwards = PageOB.canNavigateForwards;
            
			[plPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:plPageVC];
			[plPageVC release];
		}
		
		if(show)
		{
            plPageVC.numberCorrect = numberCorrect;
            plPageVC.numberIncorrect = numberIncorrect;
            
            [plPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}
	}
    else if([PageOB.pageType isEqualToString:@"DesignerSlide"])
	{
		dsPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)dsPageVC == [NSNull null])
		{
			dsPageVC = [[DesignerPageViewController alloc] init];
			dsPageVC.pageOB = PageOB;
			dsPageVC.userData = userData;
			dsPageVC.PID = [PID intValue];
            dsPageVC.PresentName = PresentName;
			dsPageVC.SlideID = SlideOB.SlideID;
			dsPageVC.PageCount = [PageOBs count];
            dsPageVC.Kiosk = KioskOB;
            dsPageVC.Show = show;
            dsPageVC.containOB = ContainOB;
            dsPageVC.SlideIndex = SlideIndex;
            dsPageVC.SlideCount = SlideCount;
            dsPageVC.isForPDF = isForPDF;
            dsPageVC.canExportToPDF = canExportToPDF;
            dsPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            dsPageVC.canNavigateForwards = PageOB.canNavigateForwards;
            
			[dsPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:dsPageVC];
			[dsPageVC release];
		}
		
		if(show)
		{
            dsPageVC.numberCorrect = numberCorrect;
            dsPageVC.numberIncorrect = numberIncorrect;

            [dsPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}
	}
	else if([PageOB.pageType isEqualToString:@"ShortAnswerQuestion"])
	{
		saPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)saPageVC == [NSNull null])
		{
			saPageVC = [ShortAnswerPageViewController alloc];
			saPageVC.pageOB = PageOB;
			saPageVC.userData = userData;
			saPageVC.PID = [PID intValue];
			saPageVC.SlideID = SlideOB.SlideID;
            saPageVC.PresentName = PresentName;
			saPageVC.PageCount = [PageOBs count];
            saPageVC.Kiosk = KioskOB;
            saPageVC.Show = show;
            saPageVC.containOB = ContainOB;
            saPageVC.SlideIndex = SlideIndex;
            saPageVC.SlideCount = SlideCount;
            saPageVC.isForPDF = isForPDF;
            saPageVC.canExportToPDF = canExportToPDF;
            saPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            saPageVC.canNavigateForwards = PageOB.canNavigateForwards;

			[saPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:saPageVC];
			[saPageVC release];
		}
		
		if(show)
		{
            saPageVC.numberCorrect = numberCorrect;
            saPageVC.numberIncorrect = numberIncorrect;
            [saPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];

		}
		
	}
	else if([PageOB.pageType isEqualToString:@"MultipleChoiceQuestion"])
	{
		mcPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)mcPageVC == [NSNull null])
		{
			mcPageVC = [MultipleChoicePageViewController alloc];
			mcPageVC.pageOB = PageOB;
			mcPageVC.userData = userData;
			mcPageVC.PID = [PID intValue];
			mcPageVC.SlideID = SlideOB.SlideID;
            mcPageVC.PresentName = PresentName;
			mcPageVC.PageCount = [PageOBs count];
            mcPageVC.Kiosk = KioskOB;
            mcPageVC.Show = show;
            mcPageVC.containOB = ContainOB;
            mcPageVC.SlideIndex = SlideIndex;
            mcPageVC.SlideCount = SlideCount;
            mcPageVC.isForPDF = isForPDF;
            mcPageVC.canExportToPDF = canExportToPDF;
            mcPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            mcPageVC.canNavigateForwards = PageOB.canNavigateForwards;

			[mcPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:mcPageVC];
			[mcPageVC release];
		}
		
		if(show)
		{
            mcPageVC.numberCorrect = numberCorrect;
            mcPageVC.numberIncorrect = numberIncorrect;

            [mcPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}	
	}else if([PageOB.pageType isEqualToString:@"Categories"])
	{
		caPageVC = [pageVCSets objectAtIndex:pageIndex];
		if((NSNull *)caPageVC == [NSNull null])
		{
			caPageVC = [CategoryPageViewController alloc];
			caPageVC.pageOB = PageOB;
			caPageVC.userData = userData;
			caPageVC.PID = [PID intValue];
			caPageVC.SlideID = SlideOB.SlideID;
            caPageVC.PresentName = PresentName;
			caPageVC.PageCount = [PageOBs count];
            caPageVC.Kiosk = KioskOB;
            caPageVC.Show = show;
            caPageVC.containOB = ContainOB;
            caPageVC.SlideIndex = SlideIndex;
            caPageVC.SlideCount = SlideCount;
            caPageVC.isForPDF = isForPDF;
            caPageVC.canExportToPDF = canExportToPDF;
            caPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            caPageVC.canNavigateForwards = PageOB.canNavigateForwards;

			[caPageVC setDelegate:self];
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:caPageVC];
			[caPageVC release];
		}
		
		if(show)
		{
            caPageVC.numberCorrect = numberCorrect;
            caPageVC.numberIncorrect = numberIncorrect;

            [caPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
		}	
	} else if ([PageOB.pageType isEqualToString:@"ScoreReport"]){
        
        srPageVC = [pageVCSets objectAtIndex:pageIndex];
        if((NSNull *)srPageVC == [NSNull null]){
            srPageVC = [ScoreReportPageViewController alloc];
            srPageVC.pageOB = PageOB;
            srPageVC.userData = userData;
            srPageVC.PID = [PID intValue];
            srPageVC.SlideID = SlideOB.SlideID;
            srPageVC.PresentName = PresentName;
            srPageVC.PageCount = [PageOBs count];
            srPageVC.Kiosk = KioskOB;
            srPageVC.Show = show;
            srPageVC.containOB = ContainOB;
            srPageVC.SlideIndex = SlideIndex;
            srPageVC.SlideCount = SlideCount;
            srPageVC.isForPDF = isForPDF;
            srPageVC.canExportToPDF = canExportToPDF;
            srPageVC.canNavigateBackwards = PageOB.canNavigateBackwards;
            srPageVC.canNavigateForwards = PageOB.canNavigateForwards;

            srPageVC.allPages = allPages;
            [srPageVC setDelegate:self];
            [pageVCSets replaceObjectAtIndex:pageIndex withObject:srPageVC];
            [srPageVC release];
        }
        
        if(show){
            srPageVC.numberCorrect = numberCorrect;
            srPageVC.numberIncorrect = numberIncorrect;
            [srPageVC transitionWithView:self.view direction:direction doTransition:shouldAnimate];
        }
    }

}


-(void)unloadViewWithPage:(int)pageIndex{
	
	if(pageIndex <0 || pageIndex >= [PageOBs count])
		return;	
	
	AD_Page *PageOB = [PageOBs objectAtIndex:pageIndex];
	
	//NSLog(@"Page No = %d", pageIndex);
	
	UserSlidePageViewController *usPageVC;
	ShortAnswerPageViewController *saPageVC;
	MultipleChoicePageViewController *mcPageVC;
	CategoryPageViewController *caPageVC;
    DesignerPageViewController *dsPageVC;
    NavigatorPageViewController *ngPageVC;
    ScoreReportPageViewController *srPageVC;
	
	if([PageOB.pageType isEqualToString:@"CurrentSlide"] || [PageOB.pageType isEqualToString:@"UserSlide"])
	{
		usPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)usPageVC != [NSNull null])
		{
			[usPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}		
	}
    else if(PageOB.pageType == @"ShortAnswerQuestion")
	{
		saPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)saPageVC != [NSNull null])
		{
			[saPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}	
	}
    else if(PageOB.pageType == @"DesignerSlide")
	{
		dsPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)dsPageVC != [NSNull null])
		{
			[dsPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}
	}
	else if(PageOB.pageType == @"NavigatorSlide")
	{
		ngPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)ngPageVC != [NSNull null])
		{
			[ngPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}	
	}
	else if(PageOB.pageType == @"MultipleChoiceQuestion")
	{		
		mcPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)mcPageVC != [NSNull null])
		{
			[mcPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}	
	}	
	else if(PageOB.pageType == @"Categories")
	{		
		caPageVC = [pageVCSets objectAtIndex:pageIndex];
		if ((NSNull *)caPageVC != [NSNull null])
		{
			[caPageVC.view removeFromSuperview];	
			[pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
		}	
	}
	else if(PageOB.pageType == @"ScoreReport")
    {
        srPageVC = [pageVCSets objectAtIndex:pageIndex];
        if ((NSNull *)srPageVC != [NSNull null]) {
            [srPageVC.view removeFromSuperview];
            [pageVCSets replaceObjectAtIndex:pageIndex withObject:[NSNull null]];
        }
    }
}

-(void)rotateForMovie:(BOOL)shouldRotate{
    [_delegate rotateForMovie:shouldRotate];
}

-(void)setUpdateStatus:(BOOL)shouldUpdate:(PageViewController*)sender{
    [_delegate setUpdateStatus:shouldUpdate:sender];
}

-(void)navigateBackwards{
    [_delegate navigateBackwards];
}

-(void)updateSecondaryChannelID:(int)key{
    [_delegate updateSecondaryChannelID:key];
}

-(void)recordNavigationHistory:(BOOL)recordToHistory :(int)pageID :(int)slideIndex{
    [_delegate recordNavigationHistory:recordToHistory :pageID :slideIndex];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    if(interfaceOrientation == UIDeviceOrientationPortrait) return YES;

    return NO;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[PageOBs release];
	[pageVCSets release];
	[PID release];
    [super dealloc];
}


@end
